package com.tianyang.yukuaifu.module.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import com.tianyang.yukuaifu.R;
import com.tianyang.yukuaifu.module.material.MaterialEditText;
import com.tianyang.yukuaifu.utils.DeviceUtil;

/**
 * Description：输入框带清空、密码显示按钮
 * Created by 薛勇军 on 2018/6/29.
 */

public class EditTextWithDel extends MaterialEditText {

    private boolean mIsInputText;

    private boolean mIsShowPwdIcon;

    private boolean mHasIcon;

    private Bitmap clearButtonBitmaps;

    private Bitmap hideButtonBitmaps;

    private Bitmap showButtonBitmaps;

    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private RectF mHideRectF;

    private RectF mClearRectF;

    private boolean isPassword;

    /**
     * 可以输入空格
     */
    public boolean inputSpace;

    public EditTextWithDel(Context context) {
        this(context, null);
    }

    public EditTextWithDel(Context context, AttributeSet attrs) {
        super(context, attrs);
        initFields(attrs, 0);
    }

    @TargetApi(21)
    public EditTextWithDel(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initFields(attrs, defStyleAttr);
    }

    public void hasIcon(boolean hasIcon) {
        this.mHasIcon = hasIcon;
        invalidate();
    }

    // 初始化布局
    public void initFields(AttributeSet attrs, int defStyleAttr) {
        if (attrs != null) {
            // 获取属性信息
            TypedArray styles = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.EditTextWithDel, defStyleAttr, 0);
            try {
                // 根据参数, 设置Icon
                isPassword = styles.getBoolean(R.styleable.EditTextWithDel_isPassword, false);
                mHasIcon = styles.getBoolean(R.styleable.EditTextWithDel_haIcon, true);
            } finally {
                styles.recycle();
            }
        }

        // 密码状态
        if (isPassword) {
            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
        }
//        else {
//            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//        }

        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!inputSpace && s.toString().contains(" ")) {
                    String[] str = s.toString().split(" ");
                    String str1 = "";
                    for (int i = 0; i < str.length; i++) {
                        str1 += str[i];
                    }
                    setText(str1);
                    setSelection(start);
                }
                if (s.length() > 0) {
                    mIsInputText = true;
                } else {
                    mIsInputText = false;
                    restorePasswordIconVisibility(mIsShowPwdIcon);
                }
                invalidate();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        clearButtonBitmaps = BitmapFactory.decodeResource(getResources(), R.drawable.ic_password_clear);
        hideButtonBitmaps = BitmapFactory.decodeResource(getResources(), R.drawable.ic_password_invisible);
        showButtonBitmaps = BitmapFactory.decodeResource(getResources(), R.drawable.ic_password_visible);

        post(new Runnable() {
            @Override
            public void run() {
                float drawableSize = dp2px(22);
                float height = getHeight() / 2;
                float top = height - drawableSize / 2;
                float bottom = top + drawableSize;
                float cLeft = getWidth() - dp2px(40);
                float cRight = cLeft + drawableSize;
                mHideRectF = new RectF(cLeft, top, cRight, bottom);

                float vLeft = getWidth() - dp2px(70);
                float vRight = vLeft + drawableSize;
                mClearRectF = new RectF(vLeft, top, vRight, bottom);
            }
        });
    }

    @Override
    protected void onDraw(Canvas canvas) {
        try {
            if (mIsInputText && mHasIcon) {
                if (isPassword) {// 密码模式
                    if (mClearRectF == null || mHideRectF == null) super.onDraw(canvas);

                    if (mIsShowPwdIcon) {// 显示切换密码模式按钮
                        canvas.drawBitmap(showButtonBitmaps, null, mHideRectF, paint);
                    } else {
                        canvas.drawBitmap(hideButtonBitmaps, null, mHideRectF, paint);
                    }
                    canvas.drawBitmap(clearButtonBitmaps, null, mClearRectF, paint);
                } else {
                    if (mHideRectF != null) {
                        canvas.drawBitmap(clearButtonBitmaps, null, mHideRectF, paint);
                    }
                }
            }
            super.onDraw(canvas);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int dp2px(float dp) {
        final float scale = DeviceUtil.SCREEN_DENSITY;
        return (int) (dp * scale + 0.5f);
    }

    // 存储状态
    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable state = super.onSaveInstanceState();
        return new PwdSavedState(state, mIsShowPwdIcon);
    }

    // 恢复状态
    @Override
    public void onRestoreInstanceState(Parcelable state) {
        PwdSavedState savedState = (PwdSavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        mIsShowPwdIcon = savedState.isShowingIcon();
        restorePasswordIconVisibility(mIsShowPwdIcon);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mHasIcon || mClearRectF == null || mHideRectF == null)
            return super.onTouchEvent(event);
        boolean clearContains = mClearRectF.contains((int) event.getX(), (int) event.getY());
        boolean hideContains = mHideRectF.contains((int) event.getX(), (int) event.getY());

        if (isPassword) {// 密码模式
            if (hideContains) {
                togglePasswordIconVisibility(); // 变换状态
                event.setAction(MotionEvent.ACTION_CANCEL);
                return false;
            }

            if (clearContains) {
                setText("");//清空文本
            }
        } else {// 不显示切换状态按钮（只有一个按钮的情况）
            if (hideContains) {//
                setText("");//清空文本
            }
        }
        return super.onTouchEvent(event);
    }

    // 变换状态
    private void togglePasswordIconVisibility() {
        mIsShowPwdIcon = !mIsShowPwdIcon;
        restorePasswordIconVisibility(mIsShowPwdIcon);
    }

    // 设置密码指示器的状态
    private void restorePasswordIconVisibility(boolean isShowPwd) {
        if (!isPassword) return;
        if (isShowPwd) {
            // 可视密码输入
            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            // 非可视密码状态
            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
        }
        // 移动光标
        setSelection(getText().length());
    }

    // 存储密码状态, 显示Icon的位置
    protected static class PwdSavedState extends View.BaseSavedState {
        private final boolean mShowingIcon;

        private PwdSavedState(Parcelable superState, boolean showingIcon) {
            super(superState);
            mShowingIcon = showingIcon;
        }

        private PwdSavedState(Parcel in) {
            super(in);
            mShowingIcon = in.readByte() != 0;
        }

        public boolean isShowingIcon() {
            return mShowingIcon;
        }

        @Override
        public void writeToParcel(Parcel destination, int flags) {
            super.writeToParcel(destination, flags);
            destination.writeByte((byte) (mShowingIcon ? 1 : 0));
        }

        public static final Parcelable.Creator<PwdSavedState> CREATOR = new Creator<PwdSavedState>() {
            public PwdSavedState createFromParcel(Parcel in) {
                return new PwdSavedState(in);
            }

            public PwdSavedState[] newArray(int size) {
                return new PwdSavedState[size];
            }
        };
    }
}
